<template>
  <div class="app-container">
    <!-- *************************************搜索区************************************* -->
    <el-form
      v-show="showSearch"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="90px"
    >
      <el-form-item :label="$t('商家名称')" prop="skuNo">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 租户类型 1-商家 2-供应商 -->
      <el-form-item label="租户类型" prop="type">
        <el-select v-model="queryParams.type" @change="handleQuery">
          <el-option label="商家" value="1" />
          <el-option :label="$t('供应商')" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 增删改查 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="tableCheck.length == 0"
          @click="handleDelete()"
          v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :disabled="tableCheck.length == 0"
          @click="handleExport" v-hasPermi="['system:user:remove']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>
    <el-table
      v-loading="loading"
        ref="TableRef"  :data="tableData"
      row-key="menuId"
      @selection-change="(row) => (tableCheck = row)"
    >
      <el-table-column
        type="selection"
        align="center"
        fixed="left"
        width="50"
      />
      <!-- 租户类型 1-商家 2-供应商 -->
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="type"
        fixed="left"
        label="租户类型"
      >
        <template slot-scope="{ row }">
          <span v-if="row.type == 1">商家</span>
          <span v-if="row.type == 2">供应商</span>
        </template>
      </el-table-column>
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="distrId"
        label="商家ID"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="name"
        :label="$t('商家名称')"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="address"
        label="商家地址"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="email"
        label="商家邮箱"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="tel"
        label="商家电话"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="wechat"
        label="商家微信"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="autoVerify"
        label="云审批自动通过"
      >
        <template slot-scope="{ row }">
          <span v-if="row.type == 2">
            {{ row.autoVerify == 0 ? "手动通过" : "自动通过" }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="applyRestrict "
        label="云申请限制"
      >
        <template slot-scope="{ row }">
          <span v-if="row.type == 1">
            {{ row.applyRestrict == 0 ? "限制" : "不限制" }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="oicq"
        label="商家oicq"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="responsibleUser"
        label="商家负责人"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="responsibleTel"
        label="	商家负责人电话"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="operateTime"
        label="商家营业时间"
      />
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="handlingFee"
        label="商家手续费"
      />
      <!-- 商家级别 1-一级 2-二级 .... -->
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="level"
        label="商家级别"
      >
        <template slot-scope="{ row }">
          <span v-if="row.level == 1">一级</span>
          <span v-if="row.level == 2">二级</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        show-overflow-tooltip
        width="200"
        prop="remark"
        :label="$t('备注')"
      />
      <el-table-column align="center" fixed="right" :label="$t('操作')" width="200">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="handleDelete(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pageTotal > 0"
      :total="pageTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 价格模式 -->
    <el-dialog
      :visible.sync="showDialog"
      :title="showName == 'add' ? '新增' : '修改'"
      width="800px"
      destroy-on-close
      :before-close="closePrice"
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          ref="elForm"
          :model="form"
          :rules="rules"
          size="small"
          label-width="150px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('商家名称')" prop="name">
                <el-input v-model="form.name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家地址" prop="address">
                <el-input v-model="form.address" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="商家电话" prop="tel">
                <el-input v-model="form.tel" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家微信" prop="wechat">
                <el-input v-model="form.wechat" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="商家类型" prop="type">
                <el-select
                  @change="(form.autoVerify = 0), (form.applyRestrict = 0)"
                  style="width: 100%"
                  v-model="form.type"
                  :placeholder="$t('请选择')"
                >
                  <el-option label="商家" :value="1" />
                  <el-option :label="$t('供应商')" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                v-if="form.type == 2"
                label="云审批自动通过"
                prop="autoVerify"
              >
                <el-switch
                  v-model="form.autoVerify"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
              <el-form-item v-else label="云申请限制" prop="applyRestrict">
                <el-switch
                  v-model="form.applyRestrict"
                  :active-value="0"
                  :inactive-value="1"
                >
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="商家负责人" prop="responsibleUser">
                <el-input v-model="form.responsibleUser" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家负责人电话" prop="responsibleTel">
                <el-input v-model="form.responsibleTel" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="商家手续费" prop="handlingFee">
                <el-input-number
                  style="width: 100%"
                  v-model="form.handlingFee"
                  controls-position="right"
                  :min="0"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家级别" prop="level">
                <el-select
                  style="width: 100%"
                  v-model="form.level"
                  :placeholder="$t('请选择')"
                >
                  <el-option label="一级" :value="1" />
                  <el-option label="二级" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="商家营业开始时间" prop="operateStartTime">
                <el-time-select
                  style="width: 100%"
                  placeholder="起始时间"
                  :picker-options="{
                    start: '06:30',
                    step: '00:10',
                  }"
                  v-model="form.operateStartTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家营业结束时间" prop="operateEndTime">
                <el-time-select
                  style="width: 100%"
                  :picker-options="{
                    start: '06:30',
                    step: '00:10',
                  }"
                  placeholder="结束时间"
                  v-model="form.operateEndTime"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="商家邮箱" prop="email">
                <el-input v-model="form.email" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家oicq" prop="oicq">
                <el-input v-model="form.oicq" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('备注')" prop="remark">
                <el-input v-model="form.remark" :rows="4" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <div style="padding: 10px">
            <el-form-item label="推荐卖家:" prop="referrerId">
              <el-select
                filterable
                style="width: 100%"
                clearable
                v-model="form.referrerId"
              >
                <el-option
                  :label="item.name"
                  :value="item.distrId"
                  :key="item.distrId"
                  v-for="item in distributorList"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="推荐卖家上级:">
              <el-select
                filterable
                style="width: 100%"
                clearable
                v-model="form.referrerSuperId"
              >
                <el-option
                  :label="item.name"
                  :value="item.distrId"
                  :key="item.distrId"
                  v-for="item in distributorList"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="推荐人:">
              <el-input type="number" v-model.number="form.referrerProportion">
                <el-button slot="prepend"> 比例 </el-button>
                <el-button slot="append">%</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="推荐人上级:">
              <el-input
                type="number"
                v-model.number="form.referrerSuperProportion"
              >
                <el-button slot="prepend"> 比例 </el-button>
                <el-button slot="append">%</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="总公司:" prop="headOfficeProportion">
              <el-input
                type="number"
                v-model.number="form.headOfficeProportion"
              >
                <el-button slot="prepend"> 比例 </el-button>
                <el-button slot="append">%</el-button>
              </el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePrice">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDistributor,
  addDistributor,
  editDistributor,
  deleteDistributor,
  exportDistributor,
} from "@/api/platform/tenantManage";
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: "tenantManage",
  data() {
    return {
      showSearch: false,
      distributorList: [],
      showName: "",
      form: {
        autoVerify: 0,
        applyRestrict: 0,
        type: 2,
        referrerProportion: "",
        referrerSuperProportion: "",
        headOfficeProportion: 100,
      },
      tableCheck: [],
      tableData: [],
      showDialog: false,
      rules: {
        // distrId: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        address: [{ required: true, message: "请输入", trigger: "blur" }],
        tel: [{ required: true, message: "请输入", trigger: "blur" }],
        applyRestrict: [{ required: true, message: "请选择", trigger: "blur" }],
        autoVerify: [{ required: true, message: "请选择", trigger: "blur" }],
        responsibleUser: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        responsibleTel: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        operateTime: [{ required: true, message: "请输入", trigger: "blur" }],
        operateStartTime: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        operateEndTime: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入", trigger: "blur" }],
        password: [{ required: true, message: "请输入", trigger: "blur" }],
        referrerProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: "blur",
          },
        ],
        referrerSuperProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: "blur",
          },
        ],
        headOfficeProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: "blur",
          },
        ],
        // handlingFee: [{ required: true, message: '请输入', trigger: 'blur' }],
        level: [{ required: true, message: "请输入", trigger: "blur" }],
        type: [{ required: true, message: "请输入", trigger: "blur" }],
        // remark: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      /**数据总条数 */
      pageTotal: 0,
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  created() {
    this.getList();
    // getDistributorList().then((res) => {
    //   const { code, data, msg } = res;
    //   if (code === 200) {
    //     console.log(`res ==>`, JSON.parse(JSON.stringify(res)));
    //     this.distributorList = data;
    //   }
    // });
  },
  methods: {
    /**验证推荐人 */
    valid(rule, value, callback) {
      console.log(
        `rule, value, ==>`,
        JSON.parse(JSON.stringify({ rule, value }))
      );
      const { field } = rule;
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form;

      if (!value) {
        return callback(new Error("请输入"));
      }

      if (field == "referrerProportion" /**推荐人 */) {
        if (+referrerProportion > 100 || +referrerProportion < 0) {
          return callback(new Error("取值范围在0~100"));
        }
      }

      if (field == "referrerSuperProportion" /**推荐人上级 */) {
        if (+referrerSuperProportion > 100 || +referrerSuperProportion < 0) {
          return callback(new Error("取值范围在0~100"));
        }
      }

      if (field == "headOfficeProportion" /**总公司 */) {
        if (+headOfficeProportion > 100 || +headOfficeProportion < 0) {
          return callback(new Error("取值范围在0~100"));
        }
      }

      const total =
        +referrerProportion + +referrerSuperProportion + +headOfficeProportion;

      if (total > 100) {
        callback(new Error("总和不能超过100"));
      }
      return callback();
    },
    closePrice() {
      this.showDialog = false;
      this.form = {
        autoVerify: 0,
        applyRestrict: 0,
        type: 2,
      };
    },
    handleAdd() {
      this.showName = "add";
      this.showDialog = true;
    },
    handleEdit(row) {
      this.showName = "edit";
      const _row = JSON.parse(JSON.stringify(row));
      const time = _row.operateTime.split("-");
      _row.operateStartTime = time[0];
      _row.operateEndTime = time[1];
      this.form = _row;
      this.showDialog = true;
    },

    handleDelete(id) {
      this.$confirm("确认删除?", "提示", {
        type: "warning",
      }).then(() => {
        let ids = [];
        if (id) {
          ids = [id];
        } else {
          ids = this.tableCheck.map((i) => i.id);
        }
        deleteDistributor(ids.toString()).then((res) => {
          if (res.code == 200) {
            this.$message({ type: 'success', message: res.msg})
;
            this.showDialog = false;
            this.getList();
          }
        });
      });
    },
    handleExport() {
      const ids = this.tableCheck.map((i) => i.id);
      console.log(`ids ==>`, ids);
      exportDistributor().then((res) => {
        if (res.code == 200) {
          this.$message({ type: 'success', message: res.msg})
;
        }
      });
    },
    submitForm() {
      // 判断分成相加是否为100
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form;
      const total =
        +referrerProportion + +referrerSuperProportion + +headOfficeProportion;

      if (total != 100) {
        return this.$message.error("比例总和必须为100");
      }
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.form));
          data.operateTime = data.operateStartTime + "-" + data.operateEndTime;
          // 新增
          if (this.showName == "add") {
            addDistributor(data).then((res) => {
              if (res.code == 200) {
                this.$message({ type: 'success', message: res.msg})
;
                this.showDialog = false;
                this.getList();
              }
            });
          }
          // 修改
          if (this.showName == "edit") {
            editDistributor(data).then((res) => {
              if (res.code == 200) {
                this.$message({ type: 'success', message: res.msg})
;
                this.showDialog = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    // 取消申请
    cancel() {},
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getDistributor(this.queryParams).then((res) => {
        this.tableData = res.rows;
        this.pageTotal = res.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.value1 = null;
      Object.keys(this.queryParams).forEach((key) => {
        this.queryParams[key] = null;
      });
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;

      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped></style>
